package com.example.dp.myapp;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by dp on 2017/11/14.
 */

public class AIDLService extends Service {

    public final String TAG = "kkww";
    private List<Book> mBooks = new ArrayList<>();


    @Override
    public void onCreate() {
        super.onCreate();
        Book book = new Book();
        book.setName("Android开发艺术探索");
        book.setPrice(28);
        mBooks.add(book);
    }

    private final BookManager.Stub mBookManager = new BookManager.Stub() {

        @Override
        public boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
            //这里进行权限验证
            String[] packages = getPackageManager().getPackagesForUid(getCallingUid());
            String packageName = null;
            if (packages != null && packages.length > 0) {
                packageName = packages[0];
            }
            Log.i(TAG, "packageName:" + packageName);
            if (!packageName.equals("com.example.dp.myapp")) {
                Log.i(TAG, "onTransact 调用失败:");
                return false;
            } else {
                Log.i(TAG, "onTransact 调用成功:");
                return super.onTransact(code, data, reply, flags);
            }

        }

        @Override
        public List<Book> getBooks() throws RemoteException {
            synchronized (this) {
                Log.e(TAG, "invoking getBooks() method , now the list is : " + mBooks.toString());
                if (mBooks != null) {
                    return mBooks;
                } else {
                    Book book = new Book();
                    book.setName("Android我是空的");
                    book.setPrice(250);
                    mBooks.add(book);
                    return mBooks;
                }

            }
        }

        @Override
        public void addBook(Book book) throws RemoteException {
            synchronized (this) {
                if (mBooks == null) {
                    mBooks = new ArrayList<>();
                }
                if (book == null) {
                    Log.e(TAG, "Book is null in In");
                    book = new Book();
                }
                //尝试修改book的参数，主要是为了观察其到客户端的反馈
                book.setPrice(2333);
                if (!mBooks.contains(book)) {
                    mBooks.add(book);
                }
                //打印mBooks列表，观察客户端传过来的值
                Log.e(TAG, "invoking addBooks() method , now the list is : " + mBooks.toString());
            }
        }
    };

    /***
     * 权限验证几个重点
     * 1.不能在OnBind中进行权限验证。因为因为在这里检查权限，是运行在服务端上的UI线程，不是Binder调用，检查的是服务端的权限。。。
     * 这里与Android开发艺术探索中讲的有区别
     *
     * 2.如果在onBind中返回null，则客户端的onServiceConnected和onServiceDisconnected都不会被调用。产生一个奇怪的bug
     *
     * 3.正确的权限验证方式是在 onTransact 通过pacakageName的方式进行权限验证。(在BookManager.Stub的实现中，重写onTransact)
     *
     @Override public boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
     //此处可进行权限检查
     String[] packages = getPackageManager().getPackagesForUid(getCallingUid());
     String packageName = null;
     if (packages != null && packages.length > 0) {
     packageName = packages[0];
     }
     Log.i(TAG, "packageName:" + packageName);
     return super.onTransact(code, data, reply, flags);
     }
     onTrasact方法是运行在服务端的Binder线程池里，是Bind调用。如上面的代码，打印出的包名会是客户端的包名，即调用者的包名是客户端。
      *
      * @param intent
     * @return
     */
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Toast.makeText(AIDLService.this, "o进入了nBind", Toast.LENGTH_SHORT).show();
        Log.e(TAG, String.format("on bind,intent = %s", intent.toString()));

//        int cheack = checkCallingOrSelfPermission("com.example.test1.permission.ACCESS_BOOK_SERVICE");
//        if(cheack == PackageManager.PERMISSION_DENIED) {
//            //对远程绑定进行权限验证
//            Toast.makeText(AIDLService.this , "被拒绝绑定了" ,Toast.LENGTH_SHORT).show();
//            return null;
//        }
        Toast.makeText(AIDLService.this, "成功绑定了", Toast.LENGTH_SHORT).show();
//        return null;
        return mBookManager;
    }
}
